/*
	此页账号注册,登录的基本用户信息集合操作
*/

package set

import (
	"BJXM_Shooting/db/mongodb"
	"fmt"
	"go.mongodb.org/mongo-driver/bson"
	"strings"
)

type User struct {
	Account  string
	Password string
	Nickname string
	Avatar   string
	Level    int
	Gold     int
}

// 查找账户
func FindUser(account string) (*User, error) {
	if strings.TrimSpace(account) == "" {
		return nil, fmt.Errorf("输入账号不可为空")
	}
	res := mongodb.Set[mongodb.XM_USERS].FindOne(mongodb.MongoContext, bson.M{"account": account})
	if res.Err() != nil {
		if res.Err().Error() == "mongo: no documents in result" {
			return nil, fmt.Errorf("账号不存在")
		}
		return nil, res.Err()
	}
	var user User
	if err := res.Decode(&user); err != nil {
		return nil, err
	}
	return &user, nil
}

// 注册账户
func Register(account, password, nickname, avatar string) error {
	account = strings.TrimSpace(account)
	if account == "" || password == "" {
		return fmt.Errorf("账号或密码不可为空")
	}

	user, err := FindUser(account)
	if err.Error() != "账号不存在" {
		return err
	}
	if user != nil {
		return fmt.Errorf("账户已存在")
	}
	user = &User{
		Account:  account,
		Password: password,
		Nickname: nickname,
		Avatar:   avatar,
	}
	_, err = mongodb.Set[mongodb.XM_USERS].InsertOne(mongodb.MongoContext, user)
	return err
}

// 登录账户
func Login(account, password string) error {
	account = strings.TrimSpace(account)
	if account == "" || password == "" {
		return fmt.Errorf("账号或密码不可为空")
	}

	user, err := FindUser(account)
	if err != nil {
		return err
	}

	if password != user.Password {
		return fmt.Errorf("账号或密码错误")
	}
	return nil
}

// 账号更新
func UserUpdate(user *User) error {
	if user == nil {
		return fmt.Errorf("更新账号传入不可为空")
	}
	_, err := mongodb.Set[mongodb.XM_USERS].UpdateOne(mongodb.MongoContext,
		bson.M{"account": user.Account},
		bson.M{
			"$set": bson.M{
				"password": user.Password,
				"level":    user.Level,
				"gold":     user.Gold,
			},
		})
	return err
}
